package com.whitedust.top70;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author A
 * @since 2025/11/11 12:55
 */

public class Top66 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<Integer> path = new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        combination(candidates, target, path, res, 0, 0);
//        Arrays.sort(candidates);
//        combination(candidates, target, path, res, 0);

        return res;
    }

    private void combination(int[] candidates, int target, List<Integer> path, List<List<Integer>> res, int sum, int start) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
        } else if (sum > target) {
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            int candidate = candidates[i];
            path.add(candidate);
            sum += candidate;
            combination(candidates, target, path, res, sum, i);
            sum -= candidate;
            path.remove(path.size() - 1);
        }
    }

    //剪枝版本，需要先给数组排序
    private void combination(int[] candidates, int target, List<Integer> path, List<List<Integer>> res, int start) {
        if (0 == target) {
            res.add(new ArrayList<>(path));
        } else if (0 > target) {
            return;
        }
        for (int i = start; i < candidates.length && target - candidates[i] >= 0; i++) {
            path.add(candidates[i]);
            combination(candidates, target - candidates[i], path, res, i);
            path.remove(path.size() - 1);
        }
    }
}
